/**
 * 方法:Array.remove(dx) 通过遍历,重构数组 功能:删除数组元素.
 * 
 * @param {}
 *            dx删除元素的下标.
 * @return {Boolean}
 */
Array.prototype.remove = function(dx) {
	if (isNaN(dx) || dx > this.length) {
		return false;
	}
	for (var i = 0, n = 0; i < this.length; i++) {
		if (this[i] != this[dx]) {
			this[n++] = this[i];
		}
	}
	this.length -= 1;
};
/**
 * 扩展数组有indexOf函数
 * 
 * @param {}
 *            obj
 * @return {}
 */
Array.prototype.indexOf = function(obj) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == obj) {
			return i;
		}
	}
	return -1;
};
// Array.forEach implementation for IE support..
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
/**
 * 数组遍历
 */
if (!Array.prototype.forEach) {
	Array.prototype.forEach = function(callback, thisArg) {
		var T, k;
		if (this == null) {
			throw new TypeError(" this is null or not defined");
		}
		var O = Object(this);
		var len = O.length >>> 0; // Hack to convert O.length to a UInt32
		if ({}.toString.call(callback) != "[object Function]") {
			throw new TypeError(callback + " is not a function");
		}
		if (thisArg) {
			T = thisArg;
		}
		k = 0;
		while (k < len) {
			var kValue;
			if (k in O) {
				kValue = O[k];
				callback.call(T, kValue, k, O);
			}
			k++;
		}
	};
}

/**
 * 原生JavaScript替换全部
 * 
 * @param {}
 *            s1
 * @param {}
 *            s2
 * @return {}a = b+c*a+a+a1
 */
String.prototype.replaceAll = function(s1, s2) {
	return this.replace(new RegExp(s1, "gm"), s2);
};
// 3 、原生JavaScript清除空格//return
// this.replace(/[(^\s+)(\s+$)]/g,"");//會把字符串中間的空白符也去掉
/*
 * String.prototype.trim = function(re) { var reExtraSpace = /^\s*(.*?)\s+$/;
 * //Sre = re.toString().trim(); return this.replace(reExtraSpace,re); };
 */
String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.ltrim = function() {
	return this.replace(/(^\s*)/g, "");
}
String.prototype.rtrim = function() {
	return this.replace(/(\s*$)/g, "");
}

/*
 * var Cnbi={ bindPanelHeaderClick:function (){
 * $(".panel-heading").click(function(){ var $o = $(this).next();
 * if($o.is(":hidden")){ $o.slideDown("show");//如果是隐藏的则显示 }else{
 * $o.slideUp("show");//如果是显示的则隐藏 } //$o.toggle("slow");
 * 
 * }); } };
 */

if (undefined == Utils || !Utils) {
	var Utils = {};
}
Utils.dimArr = [];
/**
 * 命名空间的方法
 * 
 * @param {}
 *            nameSpaceName
 */
Utils.register = function(nameSpaceName) {
	var nsArray = nameSpaceName.split('.');
	var sEval = "";
	var sNS = "";
	for (var i = 0; i < nsArray.length; i++) {
		if (i != 0)
			sNS += ".";
		sNS += nsArray[i];
		sEval += "if (typeof(" + sNS + ")=='undefined')" + "{ " + sNS
				+ "=new Object(); }";
		// eval是将参数作为代码来执行的。
		continue;
	}
	if (sEval.length > 0)
		eval(sEval);
};
Utils.openWin=function(bean){
	 var url = "http://"+Utils.getHost()+"/ctcesims/upload.cnbi?read=1&path="+bean.path+encodeURI(bean.sname)+bean.ext,
	 x = screen.width/2 - 1180/2,
	 y = screen.height/2 - 720/2;
   //  alert(url);
     window.open(url, '_blank','height=720,width=1180,left='+x+',top='+y);
}
Utils.changeIframe=function(bean){
	   if( Utils["reportConfig"].flag == false){
	      Utils.showMsg(Utils["reportConfig"].text);
	      return;
	   }
       var url = Utils["reportConfig"].text+"upload.cnbi?read=1&path="+bean.path+encodeURI(bean.sname)+bean.ext;
	   var size = $("#reportIframeId").size();
	   var msg = '<iframe id="reportIframeId" src="'+url+'" width=100% height=700px marginwidth=0 marginheight=0 vspace=0 hspace=0 frameborder=0 scrolling=no id="mainFrameId"></iframe>';
	   $("#content").empty().append(msg);
	    $("body").eq(0).css("overflow","hidden")
	   levelNav(bean);

}
/**
 * 错误信息显示的方法
 * 
 * @param {}
 *            msg
 */
Utils.showMsg = function(msg) {
	alert(msg);
};
/**
 * 信息显示在控制台 因为IE问题 所有信息显示有这里搞一下
 * 
 * @param {}
 *            msg
 */
Utils.console = function(msg) {
	if (window.console) {
		console.info(msg);
	} else {
		//alert("您用的是IE10以下内核心的浏览器!" + msg);
	}
};
/**
 * 获取str1字符串中str2字符的个数
 * 
 * @param {}
 *            str1
 * @param {}
 *            str2
 * @return {}
 */
Utils.getCount = function(str1, str2) {
	var r = new RegExp(str2, "gi");
	return str1.match(r).length;
};
/**
 * 数据格式化 并且千分位显示
 * 
 * @param {}
 *            num 数据
 * @param {}
 *            cent 保留几位
 * @return {}
 */
Utils.formatNumber = function(num, cent) {
	num = num.toString().replace(/\$|\,/g, '');
	if (isNaN(num))// 检查传入数值为数值类型.
		return num;
	if (isNaN(cent))// 确保传入小数位为数值型数值.
		cent = 0;
	cent = parseInt(cent);
	cent = Math.abs(cent);// 求出小数位数,确保为正整数.

	var sign = (num == (num = Math.abs(num)));// 获取符号(正/负数)
	// Math.floor:返回小于等于其数值参数的最大整数
	num = Math.floor(num * Math.pow(10, cent) + 0.50000000001);// 把指定的小数位先转换成整数.多余的小数位四舍五入.
	var cents = num % Math.pow(10, cent); // 求出小数位数值.
	num = Math.floor(num / Math.pow(10, cent)).toString();// 求出整数位数值.
	cents = cents.toString();// 把小数位转换成字符串,以便求小数位长度.
	while (cents.length < cent) {// 补足小数位到指定的位数.
		cents = "0" + cents;
	}
	// 对整数部分进行千分位格式化.
	for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
		num = num.substring(0, num.length - (4 * i + 3)) + ','
				+ num.substring(num.length - (4 * i + 3));

	if (cent == 0) {
		return (((sign) ? '' : '-') + num);
	}
	return (((sign) ? '' : '-') + num + "." + cents);
};
/**
 * 设置localstorage
 * 
 * @param {}
 *            key
 * @param {}
 *            value
 */
Utils.setLocalStorage = function(key, value) {
	key = encodeURIComponent(key);
	value = encodeURIComponent(value);
	if (window.localStorage) {
		localStorage.setItem(key, value);
	} else {
		Cookie.write(key, value);
	}
};
/**
 * 通过key从本地localstorage中取值
 * 
 * @param {}
 *            key
 * @return {}
 */
Utils.getLocalStorage = function(key) {
	key = encodeURIComponent(key);
	var value = window.localStorage ? localStorage.getItem(key) : Cookie
			.read(value);
	return decodeURIComponent(value);

};
/**
 * easyui 用到的排序的方法
 * 
 * @param {}
 *            a
 * @param {}
 *            b
 * @return {}
 */
Utils.sortOrder = function(a, b) {
	a = a.toString();
	b = b.toString();
	if (a != 0 && a != undefined) {
		a = parseFloat(a.replaceAll(",", '') - 0);
	}
	if (b != 0 && b != undefined) {
		b = parseFloat(b.replaceAll(",", '') - 0);
	}
	return ((a - 0) > (b - 0) ? 1 : -1);
};
/**
 * 工业或商业公司id 不传的话默认为登录人公司的spcode
 * 
 * @param {}
 *            id
 * @return {}
 */
Utils.getParams = function(id) {
	var year = $("select[name=year]").eq(0).val(), month = $("select[name=month]")
			.eq(0).val(), unit = $("select[name=unit]").eq(0).val();
	if (month.length == 1) {
		month = "0" + month;
	}
	var period = year + month;
	return {
		period : period,
		unit : unit
	};
};
Utils.applyIf = function(o, c) {
	if (o) {
		for (var p in c) {
			if (o[p] != 'undefined') {
				o[p] = c[p];
			}
		}
	}
	return o;
},
// 模仿StringUtils
Utils.isBlank = function(obj) {
	if (typeof(obj) == 'string') {
		return (obj == undefined || obj == null || obj == '');
	} else {
		return (obj == undefined || obj == null);
	}
};
Utils.isNotBlank = function(obj) {
	if (typeof(obj) == 'string') {
		return (obj != undefined && obj != null && obj != '');
	} else {
		return (obj != undefined && obj != null);
	}
};
Utils.StringBuffer = function() {
	this._strings_ = [];
	this.append = function(str) {
		this._strings_.push(str);
		return this;
	};
	this.toString = function() {
		return this._strings_.join("");
	};
};
Utils.getProjectName = function() {
	var strFullPath = window.document.location.href, strPath = window.document.location.pathname, pos = strFullPath
			.indexOf(strPath), prePath = strFullPath.substring(0, pos), postPath = strPath
			.substring(0, strPath.substr(1).indexOf('/') + 1);
	return postPath;
};
Utils.getBasePathUrl = function() {
	return "http://" + Utils.getHost() + Utils.getProjectName() + "/";
};
Utils.getHost = function(url) {
	var host = "null";
	if (typeof url == "undefined" || null == url) {
		url = window.location.href;
	}
	var regex = /^\w+\:\/\/([^\/]*).*/;
	var match = url.match(regex);
	if (typeof match != "undefined" && null != match) {
		host = match[1];
	}
	return host;
};
Utils.createChart = function(bean){
	 CnbiSoft.setCurrentRenderer('JavaScript');
	var chartId = bean["domId"] + "chartId", myChart = {};
	if (CnbiSoft(chartId)) {
		myChart = CnbiSoft(chartId);
	} else {
		myChart = new CnbiSoft(Utils.basePath + "resources/js/charts/swf/"+ bean["swf"] + ".swf", chartId, "98%", bean["heigth"]?bean["heigth"]:'100%',"0");
	}
	myChart.setJSONData(bean["data"]);
	myChart.render(bean["domId"]);
}
/**
 * 生成随即颜色
 * 
 * @return {}return "hsb(" + Math.random() + ", 1, 1)";
 */
Utils.getRandomColor = function() {
	return '#'+ ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
}
Utils.formatFloat=function (src, pos) {
		var result = Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos)-0;
		if(result==0)result=0.00;
	  return result;

}
Utils.millon=function(ss){
	if (ss < 0) {
		var s = Math.abs(ss)
		s = s.toString();
		if (isNaN(s))
			alert("invalid value");
		s = s.replace(/^(\d*)$/, "$1.");
		s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
		s = s.replace(".", ",");
		var re = /(\d)(\d{3},)/;
		while (re.test(s))
			s = s.replace(re, "$1,$2");
		s = s.replace(/,(\d\d)$/, ".$1");
		s = s.replace(/^\./, "0.");
		return "-" + s;
	} else {
		s = ss.toString();
		if (isNaN(s))
			return "invalid value";
		s = s.replace(/^(\d*)$/, "$1.");
		s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
		s = s.replace(".", ",");
		var re = /(\d)(\d{3},)/;
		while (re.test(s))
			s = s.replace(re, "$1,$2");
		    s = s.replace(/,(\d\d)$/, ".$1");
		return s.replace(/^\./, "0.");
	}
}
Utils.getDimArrByMap=function(map){
        var dimArr = [];
         for(var key in map){//JSON.parse(key)
         	var field = eval("("+key+")")["field"];
		    dimArr.push(field);
		  }
		  Utils.dimArr = dimArr ;
     }
Utils.mask=function(id){
		if(!id)id = "content";//，即将呈现结果，请稍做等候
	    $("#"+id).mask("正在努力为您加载数据");
	}
Utils.unmask=function(id){
	    if(!id)id = "content";
	    $("#"+id).unmask();
}
Utils.getDimParams = function(arr){
		var  dimArr = Utils.dimArr;
    	var bean={};
    	for(var i=0,len=dimArr.length;i<len;i++){
    	    bean[dimArr[i]] = $("#"+dimArr[i]).val();
    	}
    	return bean;
    };
/**
 * 1  加减
 * 2  乘除
 */
Utils.judgeFormulaType=function(exp){
    	var bean = {};
         if(exp.indexOf("/") != -1 || exp.indexOf("*") != -1){
         	  bean["type"] = 2;
         	  bean["text"] = "乘除";
         }else{
              bean["type"] = 1;
         	  bean["text"] = "加减";
         }
         return bean;
    }
Utils.cls = "btn-primary";    
Utils.getDimInfo=function(dim){
      var dimLen = 0,value=[];
      $("dd[name="+dim+"] >a").each(function(index,o){
	     if($(o).hasClass(Utils.cls)){
	       dimLen++;
	       value.push({scode:$(o).attr("scode"),name:$(o).text()});
	     }
      });
      var dimName = $("dd[name="+dim+"] >a").parent().prev().text();
      return {dim:dim,size:dimLen,dimName:dimName,value:value};
    }
Utils.createDrillTableBody=function(industry,bean){
    	var category =[];
    	for(var i=1;i<13;i++){
    	  category.push({label:i+"月"});
    	}
    	var tr = "",categories = [{category:category}],dataset = [],color=["A66EDD","F6BD0F"],k=0,year = [];
    	for(var key in bean){
    	   tr+="<tr><th>"+key+"</th>";
    	     var arr = bean[key],temp={seriesname:key,color:color[k]},data=[];
    	      for(var i=0;i<12;i++){
    	      	 var value = arr[i]["indicatorBean"]["datas"];
    	      	 data.push({value:value});
    	          tr+="<td title='"+arr[i]["indicatorBean"]["fun"]+"'>"+Utils.formatNumber(value,2)+"</td>";
    	      }
    	  year.push(key);
    	   tr+="</tr>";
    	   k++;
    	   temp["data"] = data;
    	   dataset.push(temp);
    	}
    	 var company = Utils.getDimInfo("company"),title=industry.sname+"【"+company["value"][0]["name"]+year.join(",")+"】趋势分析",$title =  $("#drillLabel");
    	 $title.text(title);
    	 if(industry["formula"]){
    	     $title.attr("title",industry.formula);
    	 }
		var styles={
			    definition: [
			      {
			        name: "XScaleAnim",
			        type: "ANIMATION",
			        duration: 0.5,
			        start: 0,
			        param: "_xScale"
			      },
			      {
			        name: "YScaleAnim",
			        type: "ANIMATION",
			        duration: 0.5,
			        start: 0,
			        param: "_yscale"
			      },
			      {
			        name: "XAnim",
			        type: "ANIMATION",
			        duration: 0.5,
			        start: 0,
			        param: "_yscale"
			      },
			      {
			        name: "AlphaAnim",
			        type: "ANIMATION",
			        duration: 0.5,
			        start: 0,
			        param: "_alpha"
			      }
			    ],
			    application: [
			      {
			        toobject: "CANVAS",
			        styles: "XScaleAnim, YScaleAnim,AlphaAnim"
			      },
			      {
			        toobject: "DIVLINES",
			        styles: "XScaleAnim,AlphaAnim"
			      },
			      {
			        toobject: "VDIVLINES",
			        styles: "YScaleAnim,AlphaAnim"
			      },
			      {
			        toobject: "HGRID",
			        styles: "YScaleAnim,AlphaAnim"
			      }
			    ]
			  };
	    var chartss =  {
			    palette: 2,
			    showvalues: 1,
			    numvdivlines: 10,
			    drawanchors: 0,
			    divlinealpha: 30,
			    alternatehgridalpha: 20,
			    setadaptiveymin: 1,
			    bordercolor:'dddddd',
			    bgcolor:'FAF0E6',
			    manageresize:1,
			    decimals:2,
			    legendAllowDrag:1
			  //  caption: industry.sname+"趋势拆线图"
			  }
			  //MSArea   MSLine
    	var obj={flag:true,swf:"MSLine",domId:"rightChart",data:{styles:styles,chart:chartss,categories:categories,dataset:dataset}};
    	$("#rightChart").empty()
    	$("#drillTabelBody").empty().append(tr);
    	$('#drill').modal('toggle');//toggle
    	$("#drillBody").mask("正加载数据")
    	 setTimeout(function(){
    	    Utils.createChart(obj);
    	    $("#drillBody").unmask()
    	},100);
    	Utils.unmask();
}

Utils.updateModel=function(industry){
	  Utils.console(industry); 
	 // alert(JSON.stringify(industry));
	  var params = Utils.getDimParams();
	   if(industry["exp"]){
	       var judgeBean = Utils.judgeFormulaType(industry.exp);
	   	     params["type"] = judgeBean.type;
	   }else{//报告来的
	   	    params["type"] = industry.type;
	   }
	   if( params["type"] == "table"){
	     Utils.showMsg("需求还没有弄清楚！等等开发中…………");return;
	   }
	    params["indicator"] = industry["indicator"];
       Utils.mask();
       function success(json){
       	   	console.info(json);
       	    Utils.createDrillTableBody(industry,json)
       };
       var url = Utils.getBasePathUrl() +"dash/drill.cnbi";
	       $.ajax({
			   type: "POST",
			   url: url,
			   data: params,
			   success:success,
			   dataType :'json',
			   async:false,
			   error:function(msg){
			     alert("查询【"+industry.sname+"】出错！");
			   }
	       });
    }
/**
 * 系统模型公共抽象类 data: { json: JSON.stringify({"name": "someValue"}) },
 * JSON.parse(b);
 * @param {}
 * params  Utils.register("Cnbi.Page");
 */
$(function() {
	$("#top5").click(function(){
				$('body,html').animate({
							scrollTop : 0
						}, 500);
				return false;
     });
	$(window).scroll(function(){
				if ($(this).scrollTop() > 100) {
					// $container.stop().animate({"top":afterheadHeight},speed*1.5);
					$('#jump li:eq(0)').fadeIn(500);
					$("#head").css({
								"background" : "url(images/bg2.gif) repeat-x 0 0"
							});
					$("#logowraper").hide();

				} else if ($(this).scrollTop() < 100) {
					// $container.stop().animate({"top":headHeight},speed*1.5);
					$('#jump li:eq(0)').fadeOut(500);
					$("#head").css({
								"background" : "url(images/bg.gif) repeat-x 0 0"
							});
					$("#logowraper").show();
				};
			});
	$.ajaxSetup({
				contentType : "application/x-www-form-urlencoded;charset=utf-8",
				complete : function(xhr, textStatus) {
					if (xhr.status == 911) {
						$("#content").unmask();
						alert("没有发现可用的用户登录的信息或会话已经销毁！请重新登录！");
						window.location = Utils.getBasePathUrl();// 返回应用首页
						return;
					}
		}
	});
	 /*$(document).bind("contextmenu",function(e){
          return false;
    });*/
});

/**
 * http://www.leidian.com/360雷电搜索提交经典验证
 * onsubmit="return !($.trim(this['q'].value) == '')"
 */
